<?php

namespace IDock\Insurance\ZSIC\Response;

use IDock\Http\Response;
use IDock\Insurance\ZSIC\Response\AllZSICResponse;
use IDock\Printer\PolicyPaymentPrinter;

class PolicyPaymentResponse extends AllZSICResponse
{

    public function resolve(): Response
    {
        $body = $this->getBody();
        if ($this->printer) {
            $this->printer = new $this->printer;
        }
        if ($body) {

            $body = str_replace('&','&amp;',$body);
            $xml = simplexml_load_string($body);
            $body = $this->objectToArray($xml);
            $errorMsg = $body['head']['resultCode'] ?? '';
            $message = $body['head']['errorMsg'] ?? '';
            $this->setBody($body);
            if ($errorMsg != '1') {
                $this->setError(  ($errorMsg ?: '') .":".$message);
                return  $this;
            }
        }

        return $this;
    }

    /**
     * @var PolicyPaymentPrinter $printer
     */
    public $printer = PolicyPaymentPrinter::class;

    public function printerInit(): Response
    {
        $data = $this->getBody()['body'] ?? [];
        $url = $data['base']['payUrl'] ?? '';
        if(empty($url)){
            $this->setError('支付失败');
            return $this;
        }
        $this->printer->payUrl = $url;
        return $this;
    }
}
